package xyz.syyrjx.utils;


import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import redis.clients.jedis.Jedis;
import xyz.syyrjx.entity.ResultInfo;
import xyz.syyrjx.entity.User;

import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis工具
 * @author Mr.Wan
 * @date 2022/10/12 - 23:09
 */
public class RedisUtil {
    private static final Jedis jedis = new Jedis("192.168.188.130",6379);
    private final static String BLACK_LIST = "black";
    private final static String BLACK_COUNT = "blackCount";


    /**
     * 是否在黑名单中
     * @param ip
     * @return
     */
    public static boolean isInBlack(String ip){
        Boolean sismember = jedis.sismember(BLACK_LIST, ip);
        return sismember;
    }

    /**
     * 添加到黑名单
     * @param ip
     */
    public static void blackAdd( String ip){
        jedis.sadd(BLACK_LIST, ip);
    }

    /**
     * 访问次数统计
     * @param ip
     * @return
     */
    public static long blackCount(String ip) {
        String s = jedis.get(ip);
        if (null == s) {
            jedis.setex(ip, 1, "1");
            return 1L;
        } else {
            jedis.incr(ip);
            Long now = Long.valueOf(s) + 1;
            return now;
        }
    }

    public static ResultInfo<User> getUser(String token){
        String s = jedis.get(token);
        User user = JSON.parseObject(s, User.class);
        if (null == user){
            return ResultInfo.fail("");
        }else {
            return ResultInfo.success(user);
        }

    }

}
